import json
import os
from utils import AuthenticatedRequest

class AuthService:
    CACHE_FILE = 'user_session.json'

    @staticmethod
    def login(account_id, password):
        """发送登录请求"""
        payload = {
            'account_id': account_id,
            'password': password
        }
        return AuthService._post_request('http://127.0.0.1:5000/login', json=payload)

    @staticmethod
    def save_session(data):
        """保存用户会话数据到缓存文件，确保清空旧数据"""
        # 清空旧的会话数据
        with open(AuthService.CACHE_FILE, 'w') as f:
            json.dump({}, f)

        # 保存新的会话数据
        with open(AuthService.CACHE_FILE, 'w') as f:
            json.dump(data, f)

    @staticmethod
    def load_session():
        """加载用户会话数据"""
        if os.path.exists(AuthService.CACHE_FILE):
            with open(AuthService.CACHE_FILE, 'r') as f:
                return json.load(f)
        return {}

    @staticmethod
    def fetch_file_data(fileid):
        """从服务器获取文档信息"""
        return AuthService._get_request(f'http://127.0.0.1:5000/file/{fileid}')

    @staticmethod
    def create_request(request, short_jwt):
        """提交请求到服务器"""
        headers = {'Authorization': f'Bearer {short_jwt}'}
        return AuthService._post_request('http://127.0.0.1:5000/request', json=request, headers=headers)

    @staticmethod
    def refresh_short_jwt():
        """使用长期 JWT 刷新短时 JWT"""
        session_data = AuthService.load_session()
        long_jwt = session_data.get('long_jwt')
        if not long_jwt:
            raise Exception('长期 JWT 不存在')

        headers = {'Authorization': f'Bearer {long_jwt}'}
        response = AuthService._post_request('http://127.0.0.1:5000/refresh', headers=headers)

        if response.status_code == 200:
            new_short_jwt = response.json().get('short_jwt')
            session_data['short_jwt'] = new_short_jwt
            AuthService.save_session(session_data)
            return new_short_jwt
        else:
            raise Exception('刷新短时 JWT 失败')

    @staticmethod
    def fetch_files(category=None):
        """获取文档列表，支持按类别查询"""
        try:
            if category:
                return AuthService._get_request(f'http://127.0.0.1:5000/files?category={category}')
            else:
                return AuthService._get_request('http://127.0.0.1:5000/files')
        except Exception as e:
            raise Exception(f"Failed to fetch files: {e}")

    @staticmethod
    def _get_request(url, **kwargs):
        """通用 GET 请求方法，确保返回 JSON 格式的字典"""
        response = AuthenticatedRequest.get(url, **kwargs)
        if response.status_code == 200:
            try:
                return response.json()  # 确保返回 JSON 格式
            except ValueError:
                raise Exception(f"GET 请求返回的不是有效的 JSON 数据: {url}")
        else:
            raise Exception(f"GET 请求失败: {response.status_code}, URL: {url}")

    @staticmethod
    def _post_request(url, **kwargs):
        """通用 POST 请求方法，确保返回 JSON 格式的字典"""
        response = AuthenticatedRequest.post(url, **kwargs)
        if response.status_code in [200, 201]:
            try:
                return response.json()  # 确保返回 JSON 格式
            except ValueError:
                raise Exception(f"POST 请求返回的不是有效的 JSON 数据: {url}")
        else:
            raise Exception(f"POST 请求失败: {response.status_code}, URL: {url}")